<template>
  <div class="table-container">
    <el-card>
      <Search @update-filter="handleFilterUpdate">
        <template v-slot:grandchild-slot>
          <slot name="custom-slot"></slot>
        </template>
      </Search>

      <el-table
          v-if="!loading && tableData.length > 0"
          :data="tableData"
          stripe
          style="width: 100%"
          @row-click="handleRowClick"
          empty-text="没有数据"
          fit:false
          size="default"
          :row-class-name="rowClassName">
        <!-- 状态列 -->
        <el-table-column fixed label="状态" min-width="30%">
          <template #default="scope">
            <img v-if="scope.row.status" src="../../assets/pass.svg" alt="Active Status"
                 style="width: 2.2vh; height: 2.2vh;"/>
          </template>
        </el-table-column>
        <el-table-column label="题目" min-width="100%">
          <template #default="scope">
            {{ scope.row.codeId }}.{{ scope.row.title }}
          </template>
        </el-table-column>
        <el-table-column label="标签" min-width="120%">
          <template #default="scope">
            <div v-if="scope.row.tags && scope.row.tags.length">
              <el-tag
                  v-for="(tag, index) in scope.row.tags"
                  :key="index"
                  type="success"
                  style="margin-right: 5px;">
                {{ tag }}
              </el-tag>
            </div>
            <el-tag v-else type="info">无标签</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="difficulty" label="困难等级" min-width="100%">
          <template #default="scope">
            <el-rate
                v-model="scope.row.difficulty"
                disabled
            />
          </template>
        </el-table-column>
        <el-table-column label="通过率" class="col-passRate">
          <template #default="scope">
            <el-progress :percentage="scope.row.passRate" show-text></el-progress>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            width="180"
            v-if="$slots.actions">
          <template #default="scope">
            <slot name="actions" :row="scope.row"></slot>
          </template>
        </el-table-column>
      </el-table>

      <!-- 骨架屏显示在表格同一位置，但仅在加载时 -->
      <div v-if="loading">
        <el-skeleton
            animated
            :rows="pageSize"
            style="width: 100%; margin-bottom: 20px;">
          <template #template>
            <el-skeleton-item variant="h3"/>
            <el-skeleton-item variant="text" :style="{ width: '90%' }"/>
            <el-skeleton-item variant="text" :style="{ width: '50%' }"/>
            <el-skeleton-item variant="text" :style="{ width: '80%' }"/>
          </template>
        </el-skeleton>
      </div>

      <!-- 分页组件，仅显示当表格有数据且不在加载时 -->
      <el-pagination
          v-if="!loading && tableData.length > 0"
          background
          layout="prev, pager, next"
          v-model:current-page="currentPage"
          :total="totalItems"
          v-model:page-size="pageSize"
          @update:current-page="handlePageChange"
          style="margin-top: 20px;"
      />
    </el-card>
  </div>
</template>


<script lang="ts" setup>
import {ref, onMounted} from 'vue';
import axios from 'axios';
import {ElMessage} from 'element-plus';
import {API_BASE_URL} from '@/config.ts';
import router from "@/router";
import Search from "./Search.vue";

// 定义组件状态
const tableData = ref([]);
const currentPage = ref(1);
const totalItems = ref(0);
const pageSize = ref(20);
const loading = ref(true);

// 保存过滤条件的状态
const filters = ref({
  title: '',
  tags: [],
  difficulty: ''
});

// 在父组件中响应子组件事件
const handleFilterUpdate = (newFilters) => {
  filters.value = newFilters;  // 更新 filters 状态
  loadData(1);  // 从第一页开始加载数据
};

const handleRowClick = (row) => {
  // 只有当 isBan 为 0 时才允许点击
  if (row.isBan === 0) {
    // 跳转到详情页面，假设详情页面路由为 '/problem-detail'
    // 传递题目的id作为参数
    router.push({path: `/problem-detail/${row.id}`});
  } else {
    ElMessage.warning('该题目已被管理员禁用，无法查看！');
  }
};

// 定义行样式
const rowClassName = ({ row }) => {
  // 根据 isBan 的值来添加不同的 CSS 类
  if (row.isBan === 1) {
    return 'warning-row'; // 警告状态
  }
  return ''; // 默认状态
};


const loadData = async (page) => {
  loading.value = true;

  // 从保存的 filters 中获取过滤条件
  const { title, tags, difficulty } = filters.value;

  const payload = {
    page: page,
    size: pageSize.value,
    title: title,
    tags: tags,
    difficulty: difficulty
  };

  try {
    const response = await axios.post(`${API_BASE_URL}/ProblemsGroup/problems`, payload, {});
    processResponse(response);
  } catch (error) {
    handleErrors(error);
  } finally {
    loading.value = false;
  }
};

const processResponse = (response) => {
  if (response.data && Array.isArray(response.data.data)) {
    response.data.data.forEach(item => {
      item.passRate = item.commitNum > 0 ? Math.round((item.passNum / item.commitNum) * 100) : 0;
    });
    tableData.value = response.data.data;
    totalItems.value = response.data.total;
  } else {
    console.error("Data not found or incorrect format:", response.data);
    ElMessage.error('数据格式不正确或未找到数据');
  }
};

const handleErrors = (error) => {
  console.error('Error fetching data:', error);
  ElMessage.error('请求数据失败！');
};

const handlePageChange = (newPage: number) => {
  currentPage.value = newPage;
  loadData(newPage);  // 在分页时加载当前页数据，并携带过滤条件
};

// 在组件挂载时，获取总条目数并加载初始数据
onMounted(() => {
  loadData(currentPage.value);
});
</script>





<style scoped>
.table-container {
  width: 100%;
  margin-top: 1.2vh;
  padding: 0;
}
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
/* 警告状态行的样式 */
.el-table .warning-row {
  background-color: #fff3cd; /* 浅黄色背景 */
  color: #856404; /* 深黄色字体 */
  cursor: not-allowed; /* 鼠标指针为禁用样式 */
}
</style>

<style scoped>
.table-container {
  width: 80%; /* 确保容器宽度是充满父容器的 */
  margin: 2.5vh auto;

}
</style>


